package com.recipedb.sprint.controller;



import com.recipedb.sprint.entity.Users;
import com.recipedb.sprint.service.UsersService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import com.recipedb.sprint.security.JwtUtil; // 导入现有 JwtUtil


@RestController
@RequestMapping("/api/users")
public class UsersController {
    // TODO: 以后实现

    private final UsersService usersService;

    public UsersController(UsersService usersService) {
        this.usersService = usersService;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, Object> request) {
        try {
            String username = request.get("username").toString();
            String phone = request.get("phone").toString();
            String password = request.get("password").toString();
            Map<String, Object> profile = (Map<String, Object>) request.get("profile");

            Map<String, Object> data = usersService.register(username, phone, password, profile);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "注册成功");
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request) {
        try {
            String account = request.get("account");
            String password = request.get("password");

            Map<String, Object> data = usersService.login(account, password);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "登录成功");
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 查看个人资料（需登录）
     */
    @GetMapping("/profile")
    public ResponseEntity<Map<String, Object>> getProfile(@RequestHeader("Authorization") String token) {
        try {
            // 关键修改：截取 "Bearer " 前缀（前端传的 Token 带前缀）
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            // 调用修改后的 getUserByToken（Service 层已适配 JwtUtil）
            Users user = usersService.getUserByToken(pureToken);
            Map<String, Object> data = usersService.getProfile(user.getUserid());

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 发送验证码（忘记密码）
     */
    @PostMapping("/send-code")
    public ResponseEntity<Map<String, Object>> sendVerifyCode(@RequestBody Map<String, String> request) {
        try {
            String phone = request.get("phone");
            Map<String, Object> data = usersService.sendVerifyCode(phone);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", data.get("msg"));
            response.put("data", Map.of("verifyCode", data.get("verifyCode")));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }


    /**
     * 重置密码
     */
    @PostMapping("/reset-pwd")
    public ResponseEntity<Map<String, Object>> resetPassword(@RequestBody Map<String, String> request) {
        try {
            String phone = request.get("phone");
            String verifyCode = request.get("verifyCode");
            String newPassword = request.get("newPassword");

            // 1. 校验手机号非空
            if (phone == null || phone.trim().isEmpty()) {
                throw new RuntimeException("手机号不能为空");
            }
            // 2. 校验验证码非空
            if (verifyCode == null || verifyCode.trim().isEmpty()) {
                throw new RuntimeException("验证码不能为空");
            }
            // 3. 校验新密码非空且长度合格（核心！解决 rawPassword 为 null 的问题）
            if (newPassword == null || newPassword.trim().isEmpty()) {
                throw new RuntimeException("新密码不能为空");
            }
            if (newPassword.length() < 6) {
                throw new RuntimeException("新密码长度不能少于6位");
            }



            usersService.resetPassword(phone, verifyCode, newPassword);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "密码重置成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }




    /**
     * 登出接口
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(@RequestHeader("Authorization") String token) {
        try {

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "登出成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

        /**
         * PATCH /api/users/profile
         *
         * 允许用户部分更新信息：
         * - username
         * - preferences (JSON)
         *
         * 示例请求：
         * PATCH /api/users/profile
         * Authorization: Bearer {token}
         * Content-Type: application/json
         *
         * {
         *   "username": "newName",p
         *   "preferences": {
         *       "budget": [25, 35],
         *       "car_types": null
         *   }
         * }
         *
         * @param token 用户登录token
         * @param updates 前端更新字段
         * @return 更新后的用户信息
         */
        @PatchMapping("/profile")
        public ResponseEntity<Map<String, Object>> patchProfile(
                @RequestHeader("Authorization") String token,
                @RequestBody Map<String, Object> updates) {

            try {
                String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
                // 1. 获取用户ID
                Users user = usersService.getUserByToken(pureToken);
                Long userId = user.getUserid();

                // 2. 调用服务层更新
                Map<String, Object> updatedInfo = usersService.updateUser(userId, updates);

                Map<String, Object> response = Map.of(
                        "code", 200,
                        "msg", "更新成功",
                        "data", updatedInfo
                );
                return ResponseEntity.ok(response);

            } catch (Exception e) {
                Map<String, Object> error = Map.of(
                        "code", 500,
                        "msg", e.getMessage()
                );
                return ResponseEntity.badRequest().body(error);
            }
        }
}
